package com.jl.core.common;

import com.alibaba.fastjson.JSONObject;
import com.jl.config.BaseResponse;
import com.jl.model.vo.UserVo;
import com.jl.service.GetUserInfoService;
import com.jl.utils.UserInfoContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MyInterception implements HandlerInterceptor {

    @Autowired
    private GetUserInfoService getUserInfoService;

    private boolean loginInterceptorEnable=true;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (loginInterceptorEnable){
            BaseResponse baseResponse = parserAuthentication(request);
            if (baseResponse.isSuccess()){
                return true;
            }
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(baseResponse.getData()));
            return false;
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoContext.remove();
    }

    private BaseResponse parserAuthentication(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ","");
        UserVo userByToken = getUserInfoService.getUserByToken(token);
        if (userByToken==null) {
            return BaseResponse.error("401", "请登录");
        }
        UserInfoContext.setUser(userByToken);
        return BaseResponse.success();
    }
}
